package 算法.leetcode.offer;

import 算法.leetcode.offer.base.ListNode;

/**
 * 定义一个函数，输入一个链表的头节点，反转该链表并输出反转后链表的头节点。
 *
 *  
 *
 * 示例:
 *
 * 输入: 1->2->3->4->5->NULL
 * 输出: 5->4->3->2->1->NULL
 *
 * @author lchenglong
 * @date 2022/3/17
 */
public class Offer24 {

    public static void main(String[] args) {
        ListNode head = new ListNode(1),next = new ListNode(2),third = new ListNode(3);
        head.next = next;
        next.next = third;
        Offer24 instance = new Offer24();
        ListNode listNode = instance.reverseList(head);
        while (listNode!=null){
            System.out.print(listNode.val+",");
            listNode = listNode.next;
        }
    }
    public ListNode reverseList(ListNode head) {
        // 边界条件
        if (head == null || head.next == null)return head;
        ListNode pre = null;
        while (true){
            // 暂存下一个节点
            ListNode tmp = head.next;
            head.next = pre;
            pre = head;
            if (tmp == null)break;
            head = tmp;
        }
        return head;
    }
}
